﻿using GN.Pay.TradeChannel.UnionPay.Response;
using GN.Pay.Utils.Net.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace GN.Pay.TradeChannel.UnionPay.Request
{
    [Serializable]
    class RefundRequest : APayRequest
    {
        public RefundRequest()
        {

        }


        public static RefundRequest CreateRefundRequest(
         ITradeChannel channel,
         IRefundApplyInfo apply,
         UnionPayConfigure config)
        {
            if (apply == null)
            {
                channel.ThrowChannelValidationException("请求的 apply 为 null");
            }
            RefundRequest request = new RefundRequest
            {
                version = "5.0.0",
                encoding = "UTF-8",
                signMethod = "01",
                txnType = "04",
                txnSubType = "00",
                bizType = "000301",
                accessType = "0",
                channelType = "07",
                backUrl = config.RefundNotifyUrl,
                orderId = apply.RefundNo,
                merId = config.ConfigureInfo.AccountId,
                origQryId = apply.TradeNo,
                txnTime = DateTime.Now.ToString("yyyyMMddHHmmss"),
                txnAmt = Convert.ToInt64(Math.Round(apply.ApplyMoney, 2) * 100)
            };
            return request;
        }

        /// <summary>
        /// 订单Id
        /// </summary>
        public string orderId { get; set; }

        /// <summary>
        /// 原流水号
        /// </summary>
        public string origQryId { get; set; }

        /// <summary>
        /// 退款金额
        /// </summary>
        public long txnAmt { get; set; }

        /// <summary>
        /// 订单发送时间
        /// </summary>
        public string txnTime { get; set; }

        /// <summary>
        /// 生成退款请求并得到响应
        /// </summary>
        /// <param name="channel"></param>
        /// <param name="config"></param>
        /// <param name="apply"></param>
        /// <returns></returns>
        public RefundResponse Build(ITradeChannel channel,
               UnionPayConfigure config,
               IRefundApplyInfo apply)
        {
            this.txnTime = DateTime.Now.ToString("yyyyMMddHHmmss");
            var param = this.BuildSignDictionary(channel, config, "signature");
            param = param.Clone(
            k =>
            {
                return k;
            }, v =>
            {
                return HttpUtility.UrlEncode(v, config.Encoding);
            });
            var resStr = HttpUtils.PostString("https://gateway.95516.com/gateway/api/backTransReq.do", param, config.Encoding);
            return new RefundResponse(channel, config, apply, resStr);
        }
    }
}
